package com.atguigu.delivery.filter;

import com.atguigu.delivery.util.DeliveryConstant;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;

@WebFilter(urlPatterns = "/DeliveryServlet/*")
public class LoginFilter extends HttpFilter {

    @Override
    protected void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        // 过滤条件：当前请求必须是登录状态才可以放行
        // 1、获取 HttpSession 对象
        HttpSession session = request.getSession();

        // 2、从会话域读取用户的登录状态
        Object sysUser = session.getAttribute(DeliveryConstant.ATTR_NAME_LOGIN_USER);

        // 3、判断 sysUser 对象是否为空
        if (sysUser == null) {
            // 4、sysUser 对象为空，表示当前请求没有登录
            // 后续操作：跳转到登录页面并且告诉用户，需要登录之后才能访问
            // [1]把提示信息存入请求域
            request.setAttribute("message", "请登录之后再操作！！！");

            // [2]把请求转发到登录页面
            request.getRequestDispatcher("/login.jsp").forward(request, response);
        } else {
            // 5、sysUser 对象非空，表示当前请求已经登录，可以放行
            chain.doFilter(request, response);
        }
    }
}
